{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# nontransitive_dice"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/nontransitive_dice.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/nontransitive_dice.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Nontransitive dice in Google CP Solver.\n",
    "\n",
    "  From\n",
    "  http://en.wikipedia.org/wiki/Nontransitive_dice\n",
    "  '''\n",
    "  A set of nontransitive dice is a set of dice for which the relation\n",
    "  'is more likely to roll a higher number' is not transitive. See also\n",
    "  intransitivity.\n",
    "\n",
    "  This situation is similar to that in the game Rock, Paper, Scissors,\n",
    "  in which each element has an advantage over one choice and a\n",
    "  disadvantage to the other.\n",
    "  '''\n",
    "\n",
    "  I start with the 3 dice version\n",
    "  '''\n",
    "     * die A has sides {2,2,4,4,9,9},\n",
    "     * die B has sides {1,1,6,6,8,8}, and\n",
    "     * die C has sides {3,3,5,5,7,7}.\n",
    "  '''\n",
    "\n",
    "  3 dice:\n",
    "  Maximum winning: 27\n",
    "  comp: [19, 27, 19]\n",
    "  dice:\n",
    "  [[0, 0, 3, 6, 6, 6],\n",
    "  [2, 5, 5, 5, 5, 5],\n",
    "  [1, 1, 4, 4, 4, 7]]\n",
    "  max_win: 27\n",
    "\n",
    "  Number of solutions:  1\n",
    "  Nodes: 1649873  Time: 25.94\n",
    "  getFailures: 1649853\n",
    "  getBacktracks: 1649873\n",
    "  getPropags: 98105090\n",
    "\n",
    " Max winnings where they are the same: 21\n",
    "   comp: [21, 21, 21]\n",
    "   dice:\n",
    "   [[0, 0, 3, 3, 3, 6],\n",
    "   [2, 2, 2, 2, 2, 5],\n",
    "   [1, 1, 1, 4, 4, 4]]\n",
    "   max_win: 21\n",
    "\n",
    "   Compare with these models:\n",
    "   * MiniZinc: http://hakank.org/minizinc/nontransitive_dice.mzn\n",
    "   * Comet: http://hakank.org/comet/nontransitive_dice.co\n",
    "\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "def main(m=3, n=6, minimize_val=0):\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver(\"Nontransitive dice\")\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "  print(\"number of dice:\", m)\n",
    "  print(\"number of sides:\", n)\n",
    "\n",
    "  #\n",
    "  # declare variables\n",
    "  #\n",
    "\n",
    "  dice = {}\n",
    "  for i in range(m):\n",
    "    for j in range(n):\n",
    "      dice[(i, j)] = solver.IntVar(1, n * 2, \"dice(%i,%i)\" % (i, j))\n",
    "  dice_flat = [dice[(i, j)] for i in range(m) for j in range(n)]\n",
    "\n",
    "  comp = {}\n",
    "  for i in range(m):\n",
    "    for j in range(2):\n",
    "      comp[(i, j)] = solver.IntVar(0, n * n, \"comp(%i,%i)\" % (i, j))\n",
    "  comp_flat = [comp[(i, j)] for i in range(m) for j in range(2)]\n",
    "\n",
    "  # The following variables are for summaries or objectives\n",
    "  gap = [solver.IntVar(0, n * n, \"gap(%i)\" % i) for i in range(m)]\n",
    "  gap_sum = solver.IntVar(0, m * n * n, \"gap_sum\")\n",
    "\n",
    "  max_val = solver.IntVar(0, n * 2, \"max_val\")\n",
    "  max_win = solver.IntVar(0, n * n, \"max_win\")\n",
    "\n",
    "  # number of occurrences of each value of the dice\n",
    "  counts = [solver.IntVar(0, n * m, \"counts(%i)\" % i) for i in range(n * 2 + 1)]\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "\n",
    "  # number of occurrences for each number\n",
    "  solver.Add(solver.Distribute(dice_flat, list(range(n * 2 + 1)), counts))\n",
    "\n",
    "  solver.Add(max_win == solver.Max(comp_flat))\n",
    "  solver.Add(max_val == solver.Max(dice_flat))\n",
    "\n",
    "  # order of the number of each die, lowest first\n",
    "  [\n",
    "      solver.Add(dice[(i, j)] <= dice[(i, j + 1)])\n",
    "      for i in range(m)\n",
    "      for j in range(n - 1)\n",
    "  ]\n",
    "\n",
    "  # nontransitivity\n",
    "  [comp[i, 0] > comp[i, 1] for i in range(m)],\n",
    "\n",
    "  # probability gap\n",
    "  [solver.Add(gap[i] == comp[i, 0] - comp[i, 1]) for i in range(m)]\n",
    "  [solver.Add(gap[i] > 0) for i in range(m)]\n",
    "  solver.Add(gap_sum == solver.Sum(gap))\n",
    "\n",
    "  # and now we roll...\n",
    "  #  Number of wins for [A vs B, B vs A]\n",
    "  for d in range(m):\n",
    "    b1 = [\n",
    "        solver.IsGreaterVar(dice[d % m, r1], dice[(d + 1) % m, r2])\n",
    "        for r1 in range(n)\n",
    "        for r2 in range(n)\n",
    "    ]\n",
    "    solver.Add(comp[d % m, 0] == solver.Sum(b1))\n",
    "\n",
    "    b2 = [\n",
    "        solver.IsGreaterVar(dice[(d + 1) % m, r1], dice[d % m, r2])\n",
    "        for r1 in range(n)\n",
    "        for r2 in range(n)\n",
    "    ]\n",
    "    solver.Add(comp[d % m, 1] == solver.Sum(b2))\n",
    "\n",
    "  # objective\n",
    "  if minimize_val != 0:\n",
    "    print(\"Minimizing max_val\")\n",
    "    objective = solver.Minimize(max_val, 1)\n",
    "    # other experiments\n",
    "    # objective = solver.Maximize(max_win, 1)\n",
    "    # objective = solver.Maximize(gap_sum, 1)\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  db = solver.Phase(dice_flat + comp_flat, solver.INT_VAR_DEFAULT,\n",
    "                    solver.ASSIGN_MIN_VALUE)\n",
    "\n",
    "  if minimize_val:\n",
    "    solver.NewSearch(db, [objective])\n",
    "  else:\n",
    "    solver.NewSearch(db)\n",
    "\n",
    "  num_solutions = 0\n",
    "  while solver.NextSolution():\n",
    "    print(\"gap_sum:\", gap_sum.Value())\n",
    "    print(\"gap:\", [gap[i].Value() for i in range(m)])\n",
    "    print(\"max_val:\", max_val.Value())\n",
    "    print(\"max_win:\", max_win.Value())\n",
    "    print(\"dice:\")\n",
    "    for i in range(m):\n",
    "      for j in range(n):\n",
    "        print(dice[(i, j)].Value(), end=\" \")\n",
    "      print()\n",
    "    print(\"comp:\")\n",
    "    for i in range(m):\n",
    "      for j in range(2):\n",
    "        print(comp[(i, j)].Value(), end=\" \")\n",
    "      print()\n",
    "    print(\"counts:\", [counts[i].Value() for i in range(n * 2 + 1)])\n",
    "    print()\n",
    "\n",
    "    num_solutions += 1\n",
    "\n",
    "  solver.EndSearch()\n",
    "\n",
    "  print()\n",
    "  print(\"num_solutions:\", num_solutions)\n",
    "  print(\"failures:\", solver.Failures())\n",
    "  print(\"branches:\", solver.Branches())\n",
    "  print(\"WallTime:\", solver.WallTime())\n",
    "\n",
    "\n",
    "m = 3  # number of dice\n",
    "n = 6  # number of sides of each die\n",
    "minimize_val = 0  # Minimizing max value (0: no, 1: yes)\n",
    "if len(sys.argv) > 1:\n",
    "  m = int(sys.argv[1])\n",
    "if len(sys.argv) > 2:\n",
    "  n = int(sys.argv[2])\n",
    "if len(sys.argv) > 3:\n",
    "  minimize_val = int(sys.argv[3])\n",
    "\n",
    "main(m, n, minimize_val)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
